import { fileURLToPath, URL } from 'node:url'
import path from 'path'
// import LegacyPlugin from '@vitejs/plugin-legacy'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import PostcssPresetEnv from 'postcss-preset-env'
import unocss from 'unocss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
// *添加移动端适配
// import PostcssPxToViewport from 'postcss-px-to-viewport-8-plugin'
// *分析打包体积的玩意
// import visualizer from 'rollup-plugin-visualizer'
import { defineConfig, loadEnv } from 'vite'
import { viteMockServe } from 'vite-plugin-mock'
// *这是添加SvgIcon用的
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { preview, server } from './proxy'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
	const ENV = loadEnv(mode, process.cwd())
	return {
		server,
		preview,
		base: ENV.VITE_PUBLIC_PATH,
		plugins: [
			vue({
				// 解决浏览器有可能崩溃
				template: { compilerOptions: { hoistStatic: false } },
				script: {
					// @ts-ignore
					propsDestructure: true
					// defineModel: true
				}
			}),
			// !用这个插件的话，svg源文件中fill属性需要直接删除掉
			createSvgIconsPlugin({
				// 指定需要缓存的图标文件夹
				iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
				// 指定symbolId格式
				symbolId: 'icon-[dir]-[name]'
			}),
			vueJsx(),
			Components({
				//自动加载的组件目录，默认值为 ['src/components']
				dirs: ['src/components'],
				//组件名称包含目录，防止同名组件冲突
				directoryAsNamespace: true,
				//指定类型声明文件，为true时在项目根目录创建
				dts: 'types/components.d.ts',
				resolvers: [
					AntDesignVueResolver({
						importStyle: false
					})
				]
			}),
			AutoImport({
				imports: ['vue', 'vue-router'],
				//为true时在项目根目录自动创建
				dts: 'types/auto-imports.d.ts',
				eslintrc: {
					enabled: true,
					filepath: './.eslintrc-auto-import.json',
					globalsPropValue: true
				},
				// 全局导入自定义的方法
				dirs: ['./src/autoImport']
			}),
			// *分析打包产物
			// visualizer({
			//     open: true,
			//     gzipSize: true,
			//     brotliSize: true,
			// }),
			// *原子化css
			unocss(),

			// 兼容低版本
			// LegacyPlugin({
			// 	// 需要兼容的目标列表，可以设置多个
			// 	targets: ['defaults', 'ie >= 11', 'chrome 52'],
			// 	// 面向IE11时需要此插件
			// 	additionalLegacyPolyfills: ['regenerator-runtime/runtime']
			// }),
			viteMockServe({
				mockPath: './src/mock',
				logger: false
			})
		],
		css: {
			postcss: {
				plugins: [
					PostcssPresetEnv({ browsers: 'last 2 versions' })
					// *添加移动端适配
					// PostcssPxToViewport({
					//     // 设计稿的视窗宽度
					//     viewportWidth: 375,
					//     // 对vant组件库单独处理
					//     exclude: [/^(?!.*node_modules\/vant)/],
					// }),
					// // 对项目中的样式文件处理
					// PostcssPxToViewport({
					//     // 设计稿的视窗宽度
					//     viewportWidth: 750,
					//     // 对src目录下文件进行转换
					//     include: [/\/src\//],
					// }),
				]
			}
		},
		resolve: {
			alias: {
				'@': fileURLToPath(new URL('./src', import.meta.url)),
				'types': fileURLToPath(new URL('./types', import.meta.url))
			}
		},
		build: {
			cssTarget: ['chrome20'],
			chunkSizeWarningLimit: 1500,
			rollupOptions: {
				treeshake: {
					preset: 'recommended',
					manualPureFunctions: ['console.log']
				},
				output: {
					assetFileNames: (assetInfo: any) => {
						const info = assetInfo.name.split('.')
						let extType = info[info.length - 1]
						if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)) {
							extType = 'media'
						} else if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(assetInfo.name)) {
							extType = 'img'
						} else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
							extType = 'fonts'
						}
						return `static/${extType}/[name]-[hash][extname]`
					},
					chunkFileNames: 'static/js/[name]-[hash].js',
					entryFileNames: 'static/js/[name]-[hash].js',
					manualChunks: {
						'antd-chunks': ['ant-design-vue']
					},
					experimentalMinChunkSize: 10240
				}
			}
		}
	}
})
